package com.vf.user.controller;

import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.DesensitizedUtil;
import com.dtflys.forest.annotation.Post;
import com.vf.common.annotation.Anonymous;
import com.vf.common.config.RuoYiConfig;
import com.vf.common.constant.Constants;
import com.vf.common.core.domain.entity.SysUser;
import com.vf.common.core.domain.model.LoginUser;
import com.vf.common.core.redis.RedisCache;
import com.vf.common.utils.MessageUtils;
import com.vf.common.utils.file.FileUploadUtils;
import com.vf.common.utils.file.MimeTypeUtils;
import com.vf.common.utils.ip.IpUtils;
import com.vf.framework.manager.AsyncManager;
import com.vf.framework.manager.factory.AsyncFactory;
import com.vf.framework.web.service.SysLoginService;
import com.vf.framework.web.service.TokenService;
import com.vf.system.common.IpSearchUtil;
import com.vf.system.domain.dto.UserLoginDTO;
import com.vf.user.domain.DTO.*;
import com.vf.user.domain.VO.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.vf.common.annotation.Log;
import com.vf.common.core.controller.BaseController;
import com.vf.common.core.domain.AjaxResult;
import com.vf.common.enums.BusinessType;
import com.vf.user.domain.Users;
import com.vf.user.service.IUsersService;
import com.vf.common.utils.poi.ExcelUtil;
import com.vf.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import static com.vf.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 * 用户Controller
 * 
 * @author LBS
 * @date 2025-06-04
 */
@RestController
@Api(tags = "用户管理")
@RequestMapping("/user/users")
public class UsersController extends BaseController {
    @Autowired
    private IUsersService usersService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisCache redisCache;


    /**
     * 查询用户列表
     */
    @PreAuthorize("@ss.hasPermi('user:users:list')")
    @GetMapping("/list")
    public TableDataInfo list(Users users) {
        startPage();
        List<Users> list = usersService.selectUsersList(users);
        return getDataTable(list);
    }

    /**
     * 导出用户列表
     */
    @PreAuthorize("@ss.hasPermi('user:users:export')")
    @Log(title = "用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Users users) {
        List<Users> list = usersService.selectUsersList(users);
        ExcelUtil<Users> util = new ExcelUtil<Users>(Users.class);
        util.exportExcel(response, list, "用户数据");
    }

    /**
     * 获取用户详细信息
     */
//    @PreAuthorize("@ss.hasPermi('user:users:query')")
    @GetMapping(value = "/{id}")
    @Anonymous
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(usersService.selectUsersById(id));
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('user:users:add')")
    @Log(title = "用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Users users) {
        return toAjax(usersService.insertUsers(users));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('user:users:edit')")
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Users users) {
        return toAjax(usersService.updateUsers(users));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('user:users:remove')")
    @Log(title = "用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(usersService.deleteUsersByIds(ids));
    }

    @ApiOperation("获取用户标签信息")
    @Anonymous
    @GetMapping("/getTagesById")
    public AjaxResult getTagesById(Long userId) {
        return AjaxResult.success(usersService.selectUsersById(userId));
    }

    @ApiOperation("获取用户信息")
    @Anonymous
    @GetMapping("/getUserById")
    public AjaxResult getUserById(Long userId) {
//        Long userId = getUserId();
        return success(usersService.getUserById(userId));
    }


    @ApiOperation("获取用户详细信息")
    @Anonymous
    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo(Long userId) {
//        Long userId = getUserId();
        return AjaxResult.success(usersService.getUserInfo(userId));
    }


    //删除账户
    @ApiOperation("删除账户")
    @Anonymous
    @DeleteMapping("/deleteUser")
    public AjaxResult deleteUser(Long userId) {
//        Long userId = getUserId();
        return AjaxResult.success(usersService.deleteUserById(userId));
    }

    //修改用户头像
//    @ApiOperation("修改用户头像")
//    @Anonymous
//    @PutMapping("/updateUserAvatar")
//    public AjaxResult updateUserAvatar(Long userId){
////        Long userId = getUserId();
//        return AjaxResult.success(usersService.updateUserAvatar(userId));
//    }

    @ApiOperation("修改用户信息")
    @Anonymous
    @PutMapping("/updateUserInfo")
    public AjaxResult updateUserInfo(UserVO userVO) {
//        Long userId = getUserId();
        return AjaxResult.success(usersService.updateUserInfo(userVO));
    }

    //用户登录
    @ApiOperation("用户登录")
    @Anonymous
    @PostMapping("/auth/login")
    public AjaxResult login(@Valid @RequestBody LoginDTO request) {
        SysUser user = new SysUser();
        BeanUtil.copyProperties(request, user);
        System.out.println(user.toString());
        user.setPhonenumber(request.getPhonenumber());
        UserVO dto = usersService.loginByPass(user);
        if (dto != null) {
            LoginUser loginUser = new LoginUser();
            AsyncManager.me().execute(
                    AsyncFactory.recordLogininfor(
                            dto.getUserName(),
                            dto.getUserId(),
                            Constants.LOGIN_SUCCESS,
                            MessageUtils.message("user.login.success")
                    )
            );
            sysLoginService.recordLoginInfo(loginUser.getUserId());
            loginUser.setUserId(dto.getUserId());
            user.setUserName(dto.getUserName());
            loginUser.setUser(user);
            String token = tokenService.createToken(loginUser);
            redisCache.setCacheObject(loginUser.getToken(), loginUser);
            dto.setPhone(DesensitizedUtil.mobilePhone(dto.getPhone()));
            dto.setToken(token);
            return AjaxResult.success("登录成功", dto);
        }
        return AjaxResult.error("登录失败");
    }

    /**
     * 用户手机号、密码注册
     *
     * @param dto
     * @return com.vf.common.core.domain.AjaxResult
     **/
    @Anonymous
    @ApiOperation(value = "用户手机号、密码注册")
    @PostMapping("/register")
    public AjaxResult registerByPass(@Valid @RequestBody RegisterDTO dto) {
        System.out.println(dto);
//        // vo转bean
//        SysUser sysUser = new SysUser();
        //验证码
//        BeanUtil.copyProperties(dto, sysUser);
//        String key = "userRegisterCode:" + dto.getPhone();
//        String code = (String) redisTemplate.opsForValue().get(key);
//        if (!code.equals(dto.getCode())) {
//            throw new ServiceException("验证码错误");
//        }
        boolean registerUser = false;
        if (!"".equals(dto.getEmail()) && dto.getEmail() != null) {
            registerUser = usersService.registerUserByEmail(dto);
        } else {
            registerUser = usersService.registerUserByPhone(dto);
        }
        if (registerUser) {
            return success("注册成功");
        }
        return error("注册失败，手机号和密码不合规");
    }

//    @Anonymous
//    @ApiOperation(value = "用户微信登录")
//    @PostMapping("/loginUser")
//    public AjaxResult loginUserWX(@Valid @RequestBody UserWxLoginVO vo) {
//        log.debug("用户code：{}", vo.getCode());
//        // 登录
//        SysUser user = usersService.loginUser(vo);
//        log.debug("用户登录返回：{}", user);
//        // 为用户生成jwt令牌
//        UserLoginDTO dto = new UserLoginDTO();
//        BeanUtil.copyProperties(user, dto);
//        return AjaxResult.success("登录成功", dto);
//    }


//    @Anonymous
//    @ApiOperation("微信小程序用户登录")
//    @PostMapping("/appletLogin")
//    public AjaxResult appletUserLogin(@Valid @RequestBody UserAppletLoginVO vo) {
//        log.debug("用户微信授权码：{}", vo.getCode());
//        UsersLoginDTO dto = usersService.appletLogin(vo.getCode());
//        if (dto.getUserId() != null) {
//            // 生成token
//            return AjaxResult.success("登录成功", dto);
//        }
//        return AjaxResult.toRegister("用户还未注册", dto.getOpenid());
//    }
//
//    @Anonymous
//    @ApiOperation(value = "微信小程序用户注册")
//    @PostMapping("/appletRegister")
//    public AjaxResult appletUserRegister(@Valid @RequestBody UserAppletRegisterVO vo) {
//        log.debug("用户信息：{}", vo);
//        usersService.appletRegister(vo);
//        return AjaxResult.success("注册成功");
//    }
//
//    @Anonymous
//    @ApiOperation(value = "微信小程序用户手机号注册")
//    @PostMapping("/appletRegisterByPhone")
//    public AjaxResult appletUserRegisterByPhone(@Valid @RequestBody UserAppletRegisterByPhoneVO vo) {
//        log.debug("用户信息：{}", vo);
//        usersService.appletRegisterByPhone(vo);
//        return AjaxResult.success("注册成功");
//    }


    @ApiOperation("修改用户信息")
    @Anonymous
    @PostMapping("/updateUserProfile")
    public AjaxResult updateUserProfile(@RequestBody UserUpdateDTO updateDTO) {
//        Long userId = getUserId();
        System.out.println(updateDTO);
        return success(usersService.updateUserProfile(updateDTO));
    }

    @ApiOperation("修改用户信息ID")
    @Anonymous
    @PostMapping("/updateUserInfo")
    public AjaxResult updateUserInfo(@RequestBody UsersUpDTO updateDTO) {
//        Long userId = getUserId();
        System.out.println(updateDTO);
        return success(usersService.updateUserInfo2(updateDTO));
    }


//    @ApiOperation("受到邀约")
//    @Anonymous
//    @PostMapping("/getReceivedInviteCount")
//    public AjaxResult getReceivedInviteCount(@RequestBody UsersUpDTO updateDTO){
////        Long userId = getUserId();
//        System.out.println(updateDTO);
//        return success(usersService.updateUserInfo2(updateDTO));
//    }

    /**
     * 受到邀约
     *
     * @param userId 用户ID
     * @return AjaxResult 包含受邀数量的结果
     */
    @ApiOperation("受到邀约")
    @Anonymous
    @GetMapping("/getReceivedInviteCount")
    public AjaxResult getReceivedInviteCount(Long userId) {
        return success(usersService.getReceivedInviteCount(userId));
    }

    /**
     * 发送邀约
     *
     * @param userId 用户ID
     * @return AjaxResult 包含发送邀约数量的结果
     *
     */
    @ApiOperation("发送邀约")
    @Anonymous
    @GetMapping("/getSentInviteCount")
    public AjaxResult getSentInviteCount(Long userId) {
        return success(usersService.getSentInviteCount(userId));
    }


    /**
     * 处理用户邀约审核
     *
     * @param appDTO 包含审核信息的数据传输对象，包括邀约ID、审核状态等
     * @return AjaxResult 包含操作结果和审核处理后的数据
     * 如果成功返回，数据中可能包含更新后的邀约状态信息
     */
    @ApiOperation("审核")
    @Anonymous
    @PostMapping("/respondToInvite")
    public AjaxResult respondToInvite(@RequestBody AppDTO appDTO) {
        return success(usersService.respondToInvite(appDTO));
    }

    /**
     * 注销用户账户
     *
     * @param user 包含用户注销信息的数据传输对象，至少包含用户ID
     * @return AjaxResult 包含操作结果和注销处理后的数据
     * 如果成功返回，数据中可能包含注销时间等信息
     */
    @ApiOperation("注销用户")
    @Anonymous
    @PostMapping("/updateUserAccount")
    public AjaxResult updateUserAccount(@RequestBody Users1 user) {
        return success(usersService.deleteUserAccount(user));
    }

//    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
//    @PostMapping("/avatar")
//    @Anonymous
//    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception
//    {
//        if (!file.isEmpty())
//        {
//            LoginUser loginUser = getLoginUser();
//            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
//            if (usersService.updateUserAvatar(loginUser.getUserId(), avatar) > 0)
//            {
//                AjaxResult ajax = AjaxResult.success();
//                ajax.put("imgUrl", avatar);
//                // 更新缓存用户头像
//                loginUser.getUser().setAvatar(avatar);
//                tokenService.setLoginUser(loginUser);
//                return ajax;
//            }
//        }
//        return error("上传图片异常，请联系管理员");
//    }


    //用经纬度定位，然后传值
    @ApiOperation("获取用户iP")
    @Anonymous
    @GetMapping("/getUserIP")
    public AjaxResult getUserIP(HttpServletRequest request) throws IOException {
        String ip = IpUtils.getIpAddr(request);
        String cityFromIp = IpSearchUtil.getCityFromIp(ip); // 传递用户IP
        log.info("用户iP：{}，城市：{}", ip, cityFromIp);
//        String addressFromIp = IpSearchUtil.getAddressFromIp(ip); // 传递用户IP
//        log.info("用户iP：{}，地区：{}", ip, addressFromIp);
        return success(IpSearchUtil.getOutboundIpAddress());
    }

}